/******************************************************************************
 * Title:     Younker Web Application Framework
 * Copyright: Copyright (c) 2004
 * Company:   YounkerSoft
 * Author: 	  Xiao Jian
 * Version:   2.0
 *****************************************************************************/
package com.younker.waf.db;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * DataSourceProvider.java
 */
public class DataSourceProvider {

	private static DataSourceProvider _instance = null;
	private static DataSource ds = null;
	private static Context ctx = null;
	private static final Log log = LogFactory.getLog(DataSourceProvider.class);

	private DataSourceProvider() {

		try {
			ctx = new InitialContext();
			Context envContext = (Context) ctx.lookup("java:/comp/env");
			ds = (DataSource) envContext.lookup("jdbc/hrmsDS");
		} catch (NamingException ex) {
			log.fatal("Can't find datasource", ex);
		} finally {
			try {
				ctx.close();
			} catch (Exception ex) {
			}
		}
	}

	public static DataSourceProvider instance() {
		if (_instance == null) {
			_instance = new DataSourceProvider();
		}
		return _instance;
	}

	public DataSource getDataSource() {
		return ds;
	}

	public Connection getConnection() {
		Connection connection = null;
		try {
			connection = ds.getConnection();

		} catch (SQLException ex) {
			log.error("Can't get an unused connection ", ex);
		}
		return connection;
	}
}
